package com.freightoa.sgl_login.presentation.screen


import android.view.MotionEvent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.freightoa.foundation.presentation.activity.BaseComposeActivity
import com.freightoa.foundation.presentation.composable.ErrorDialog
import com.freightoa.foundation.presentation.composable.ProgressIndicator
import com.freightoa.foundation.result.Router
import com.freightoa.foundation.result.Routes
import com.freightoa.foundation.utlis.KeyBoardUtil
import com.freightoa.sgl_login.R
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class LoginActivity : BaseComposeActivity<LoginState, LoginIntent, LoginViewModel>() {
    @Inject
    lateinit var router: Router
    override fun getViewModelClass(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun createInitialState() = LoginState.Loading

    @Composable
    override fun Content(
        viewModel: LoginViewModel,
        state: LoginState,
        sendIntent: (LoginIntent) -> Unit,
        modifier: Modifier
    ) {
        LoginPage { username, password ->
            KeyBoardUtil.hideKeyBoard(this, currentFocus)
            sendIntent(LoginIntent.Login(username, password))
        }
        when (state) {
            is LoginState.Loading -> ProgressIndicator()
            is LoginState.Success -> {

                router.navigateTo(this, Routes.HOME)
                finish()
                // startActivity(Intent(this, HomeActivity::class.java))
            }

            is LoginState.Error -> ErrorDialog(
                showError = true,
                onDismiss = { viewModel.handleIntent(LoginIntent.Idle) }, // 关闭时更新状态
                message = state.errorMessage ?: "error"
            )

            LoginState.Idle -> {}
        }
    }
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP) {
            val v = currentFocus
            // 如果不是落在EditText区域，则需要关闭输入法
            if (KeyBoardUtil.isHideKeyboard(v, ev)) {
                KeyBoardUtil.hideKeyBoard(this, v)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onPause() {
        super.onPause()
        KeyBoardUtil.hideKeyBoard(this, currentFocus)
    }

    @Preview(showBackground = true)
    @Composable
    fun PreviewView() {
        var username by remember { mutableStateOf("") }
        LoginPage { name, password ->
            username = name + password
        }
    }


    @Composable
    fun LoginPage(
        loginClick: (String, String) -> Unit
    ) {
        val blue = Color(0xFF1A73E8)
        val gray = Color(0xFF9E9E9E)
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(color = Color.White),
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 顶部 Logo
            Image(
                painter = painterResource(id = R.drawable.login_image), // 替换为实际图片资源
                contentDescription = "SGL Logo",
                modifier = Modifier.padding(top = 150.dp, bottom = 75.dp)
            )
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 32.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                var username by remember { mutableStateOf("") }
                OutlinedTextField(
                    singleLine = true,
                    value = username,
                    onValueChange = { username = it },
                    placeholder = { Text("User Name") },
                    modifier = Modifier.fillMaxWidth()
                )

                var password by remember { mutableStateOf("") }
                OutlinedTextField(
                    singleLine = true, // 关键参数
                    value = password,
                    onValueChange = { password = it },
                    placeholder = { Text("Password") },
                    modifier = Modifier.fillMaxWidth(),
                    visualTransformation = PasswordVisualTransformation()
                )

                Button(
                    onClick = { loginClick(username, password) },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(4.dp),
                    colors = ButtonDefaults.buttonColors(blue)
                ) {
                    Text("Login", color = Color.White)
                }
            }

            // 底部版权信息
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.BottomCenter
            ) {
                Text(
                    text = "© 2025 Freight OA Inc. All rights reserved.",
                    color = gray,
                    modifier = Modifier.padding(bottom = 16.dp),
                    fontSize = 12.sp
                )
            }

        }
    }

}